package com.edushare.common.dao;

import java.util.List;

import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.CourseGrade;
import com.edushare.common.vo.CourseInstances;
import com.edushare.common.vo.GradeKey;
import com.edushare.common.vo.Users;

public class CourseGradeDAO extends CayenneBasedDAO {
	public CourseGradeDAO(ORMInterface ormInterface) {
		super(ormInterface);
	}

	public void addCourseGrade(Users user, CourseInstances cInst, Double marks,
			GradeKey gKey, String comments, int evalType, int entryType) {
		CourseGrade cGrade = getUserCourseGrade(user, cInst);
		if(cGrade == null){
			cGrade = new CourseGrade();
			getDataContext().registerNewObject(cGrade);
		}
		cGrade.setManualEntry(entryType);
		cGrade.setComments(comments);
		cGrade.setCourse(cInst);
		cGrade.setGradeKey(gKey);
		cGrade.setMarks(marks);
		cGrade.setUser(user);
		cGrade.setEvaluationType(evalType);
		getDataContext().commitChanges();
	}
	
	public void removeCourseGrades(Users user, CourseInstances cInst){
		CourseGrade cGrade = getUserCourseGrade(user, cInst);
		if(cGrade == null)
			return;
		getDataContext().deleteObject(cGrade);
		getDataContext().commitChanges();
	}

	public CourseGrade getUserCourseGrade(Users user, CourseInstances cInst) {
		List<CourseGrade> grades = user.getCourseGrades();
		for (CourseGrade g : grades) {
			if (g.getCourse() == cInst)
				return g;
		}
		return null;
	}
	
	public boolean isManualEntry(Users user, CourseInstances cInst){
		CourseGrade g = getUserCourseGrade(user, cInst);
		if(g==null)
			return false;
		if(g.getManualEntry() != CourseGrade.CALCULATED_ENTRY)
			return true;
		return false;
	}

	public List<CourseGrade> getCourseGrades(CourseInstances cInst) {
		return cInst.getCourseGrades();
	}
}
